<template>
  <div class="details" id="basic-demo">

    <div class="primary" v-if="showButton" @click="primarytop">
      <icon-to-top />
    </div>
    <div class="spinnu" v-if="aspindot">
      <a-spin dot />
    </div>

    <div class="spinnu" v-if="pfdspin">
      <a-spin dot tip="正在下载pdf" />
    </div>
    <div class="imgdetails" id="pdfWrap">
      <!-- <a-back-top
          target-container="#basic-demo"
          :style="{ position: 'absolute', bottom: '20px', right: '20px' }"
        /> -->
      <a-button style="float: right;margin: 10px 20px 0 0;" type="primary" class="notShowPdf" @click="savePdf"
        v-if="notshowMore">下载</a-button>
      <p class="details-p"  style="font-size: 13px;">
        <span style="font-size: 16px">
          <span style="margin-right: 10px;cursor: pointer;font-size: 22px;" @click="runturgo"><icon-undo /></span>
          {{ info.SaveName }}</span>
        <br />
        <span style="font-size: 13px;">编号：{{ info.singleCode }}</span>
        <span style="font-size: 13px;">测评时间：{{ info.AddTime }}</span> <br />
        姓名：{{ info.ClassName }}
      </p>
      <!-- <div class="details-img">
        <img :src="info.qrcodeTeacher" v-if="info.qrcodeTeacher" alt="" />
      </div>
      <p class="details-p" style="font-size: 13px;">请微信联系指导老师</p> -->

      <div class="content-area" id="contentToConvert">
        <!-- <div> 测评概况</div> / -->

        <div class="content-detsils2">
          <Details1 v-if="table1.length > 0" :table1="table1" :rotesData="rotesData" :typesArray="typesArray"
            :scoresArray="scoresArray" :avgSubRotes="avgSubRotes" :avgTates="avgTates"></Details1>
        </div>
        <div class="content-detsils2">
          <Details2 v-if="klScoreLevdata" :klScoreLev="klScoreLevdata" />
        </div>
        <div class="content-detsils2">
          <Details3 v-if="skillLev" :skillLev="skillLev" />
        </div>
        <div class="content-detsils2">
          <Details4 v-if="capacityLev" :capacityLev="capacityLev" />
        </div>
        <div class="content-detsils2">
          <Details5 v-if="knowledgeName.length > 0" :knowledgeName="knowledgeName" :info="info" :rates="rates"
            :brknowledgesName="brknowledgesName" />
        </div>
        <div class="content-detsils2">
          <Details6 v-if="klScoreLevdata" :klScoreLevdata="klScoreLevdata" />
        </div>
        <div class="content-detsils2 notShowPdf">
          <Details7 v-if="monopolize" :monopolize="monopolize" />
        </div>
        <div class="content-detsils2 notShowPdf">
          <Details8 v-if="monopolize1" :monopolize="monopolize1" />
          <div class="bottomlist">
            温馨提示：另有配套《课后自适应训练》内含三大板块①经典母题②实战演练③错题再现，帮助考生举一反三，实现从“学过”到“学会”的转变！
          </div>
        </div>
      </div>

      <!-- <button @click="downloadPdf">下载 PDF</button> -->
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, watch, nextTick } from "vue";
import { MyHomeworkhtmltopdf, postReportgetData } from "@/api/diagnosis";
import Details1 from "./center/details1.vue";
import Details3 from "./center/details3.vue";
import Details4 from "./center/details4.vue";
import Details5 from "./center/details5.vue";
import Details6 from "./center/details6.vue";
import Details7 from "./center/details7.vue";
import Details8 from "./center/details8.vue";
import Details2 from "./center/details2.vue";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import * as echarts from "echarts/core";
import useUserStore from "@/store/modules/user";
import { useRouter, useRoute } from "vue-router";
import { Message } from "@arco-design/web-vue";
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const aspindot = ref(false);
// const receivedData = route.query.VID;
const subjectID = userStore.$state.subjectID;
const permission = JSON.parse(localStorage.getItem("permission") as any);
const table1 = ref([]);
const knowledgeName = ref([]);
const typesArray = ref();
const scoresArray = ref();
const rates = ref();
const brknowledgesName = ref();
const monopolize = ref();
const monopolize1 = ref();
const formname = reactive({
  gid: 0, //年级
  sid: 0, //学科
  paperID: 0, //试卷
  ctrID: 0, //
});

const rotesData = reactive({
  rotes: 0,
  totle: 0,
});

const klScoreLevdata = ref();
const skillLev = ref();
const capacityLev = ref();
const avgSubRotes = ref();
const info = reactive({
  SaveName: "",
  singleCode: "",
  AddTime: "",
  ClassName: "", //学生名
  OrganName: "", //学校名
  DocDiff: 0, //难度
  qrcodeTeacher: "",
});

const notshowMore = ref(true);
const savePdf = () => {
  Message.success("下载中...");
  const pdf = new jsPDF('p', 'mm', 'a4'); // 明确指定方向和单位
  const pdfWrap = document.getElementById("pdfWrap");

  if (!pdfWrap) {
    console.error("Element with id 'pdfWrap' not found.");
    return;
  }

  html2canvas(pdfWrap, {
    // 可选：提高截图质量
    scale: 2, // 像素密度，2 表示 2 倍，让图片更清晰
    useCORS: true, // 允许跨域图片
    allowTaint: true, // 允许污染的画布（有安全风险，谨慎使用）
    // 👇 关键：添加 ignoreElements 配置
    ignoreElements: (element) => {
      // 如果元素包含 'notshowpdf' class，则返回 true，表示忽略它
      return element.classList && element.classList.contains('notShowPdf');
    }
  }).then((canvas) => {
    const imgData = canvas.toDataURL('image/png');
    const imgWidth = 210; // A4 宽度，单位 mm
    const imgHeight = (canvas.height * imgWidth) / canvas.width; // 计算图片在 PDF 中的高度

    let heightLeft = imgHeight; // 剩余要绘制的高度
    let position = 0; // 当前绘制的 Y 坐标


    // 重新创建一个不带初始页的 pdf 实例（但 jsPDF 总是有一页，所以我们先添加图片到第一页）
    pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, undefined, 'FAST');
    heightLeft -= 297; // 减去第一页能容纳的高度

    // 如果剩余高度大于 0，说明需要更多页
    while (heightLeft > 0) {
      pdf.addPage(); // 添加新页
      position = position - 297; // 向上移动 297mm (一页的高度)
      pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, undefined, 'FAST');
      heightLeft -= 297;
    }
    // --- 关键修改结束 ---

    // ✅ 将 save() 移到 .then() 内部，确保所有操作完成后才保存
    pdf.save(info.ClassName+"-"+info.SaveName+".pdf");
  }).catch((error) => {
    // 处理可能出现的错误
    console.error("Error generating PDF:", error);
  });
};
const avgTates = ref();
const Report = () => {
  aspindot.value = true;
  // route.query.SubjectID
  formname.gid = permission.GradeID;
  formname.ctrID = route.query.CTRID;
  formname.sid = route.query.SubjectID;
  formname.paperID = route.query.SaveID;
  // route.query.SaveID
  postReportgetData(formname).then((res: any) => {
    const datalist = res[1].list;
    const infodata = datalist.info[0];
    info.SaveName = infodata.SaveName;
    info.singleCode = infodata.singleCode;
    info.AddTime = infodata.AddTime;
    info.ClassName = infodata.ClassName;
    info.OrganName = infodata.OrganName;
    info.DocDiff = infodata.DocDiff;
    info.qrcodeTeacher = infodata.qrcodeTeacher;
    avgTates.value = [datalist.avgTates, datalist.rotes];

    table1.value = Object.values(datalist.testInfo);
    knowledgeName.value = Object.values(datalist.knowledgeName).map(
      (item: any) => ({
        name: item[0], // 取 name（第 1 个元素）
        value: parseInt(item[1]), // 取 value（第 3 个元素，转为数字）
      })
    );
    rotesData.rotes = datalist.rotes;//(datalist.rotes / datalist.totle) * 100;
    rotesData.totle = (10000 - datalist.rotes * 100) / 100;//datalist.totle;
    console.log(rotesData);
    // Object.values(datalist.testInfo)
    typesArray.value = Object.values(datalist.testInfo).map(
      (item: any) => item.TypesName
    );
    scoresArray.value = Object.values(datalist.testInfo).map(
      (item: any) => item.getScoreRates
    );
    // datalist.rates

    rates.value = datalist.rates.map((item: any) => item.rates);
    brknowledgesName.value = datalist.rates.map(
      (item: any) => item.brknowledgesName
    );
    // 专属1v1
    const exclusive = Object.values(datalist.jiqiaoVideo);
    const exclusive1 = Object.values(datalist.zxVideo);
    monopolize.value = exclusive;
    monopolize1.value = exclusive1;
    klScoreLevdata.value = JSON.parse(datalist.klScoreLev);
    skillLev.value = JSON.parse(datalist.skillLev);
    capacityLev.value = JSON.parse(datalist.capacityLev);
    // monopolize1.value= exclusive[1]
    const tifen = parseInt(((datalist.avgTates - datalist.rotes) / 100) * (parseInt(datalist.totle / datalist.rotes * 100)));
    if (datalist.rotes == 0) {
      avgSubRotes.value = datalist.avgTates;
    } else if (datalist.rotes < datalist.avgTates) {
      if (tifen >= 5) {
        avgSubRotes.value = tifen;
      } else {
        avgSubRotes.value = 5;
      }
    } else {
      avgSubRotes.value = parseInt((1 - datalist.rotes / 100) * parseInt((datalist.totle / datalist.rotes * 100)));
    }
    // avgSubRotes.value = parseInt(
    //   ((datalist.avgTates - datalist.rotes) / 100) *
    //     parseInt((datalist.totle / datalist.rotes) * 100)
    // );
    aspindot.value = false;

    sendPageDataToBackend();
  });
};
// 新函数：将页面数据发送给后端
const pfdspin = ref(false);
// 新函数：将页面数据及样式发送给后端
const sendPageDataToBackend = async () => {
  await nextTick(); // 等待DOM更新
  pfdspin.value = false;
  try {
    const imgdetailsElement = document.querySelector(".imgdetails");
    if (!imgdetailsElement) {
      console.error("未找到.imgdetails元素");
      pfdspin.value = false;
      return;
    }

    // 1. 获取所有样式（包括主页面和子页面）
    const styles = await Promise.all(
      Array.from(
        document.querySelectorAll('style, link[rel="stylesheet"]')
      ).map(async (styleElement) => {
        if (styleElement.tagName === "STYLE") {
          return styleElement.innerHTML;
        } else {
          try {
            const response = await fetch(styleElement.href);
            if (response.ok) {
              return await response.text();
            }
          } catch (error) {
            console.error(
              `Failed to fetch external CSS: ${styleElement.href}`,
              error
            );
          }
          return "";
        }
      })
    );
    const finalStyles = styles.join("\n");

    // 假设 imgdetailsElement 已经定义
    const imgElements = imgdetailsElement.querySelectorAll("img");
    const baseUrl = "http://123.57.81.131:8081/";

    for (const img of imgElements) {
      let src = img.src;
      // 检查 src 是否已经是完整的 URL，如果不是则添加前缀
      if (!src.startsWith("http")) {
        src = baseUrl + src;
      }
      img.src = src;
    }

    // 检查 echarts 是否正确引入
    if (typeof echarts === "undefined") {
      console.error("ECharts 库未正确引入");
      return;
    }

    // 处理 ECharts 图表
    const echartsElements = imgdetailsElement.querySelectorAll(".echarts");
    for (const echartsElement of echartsElements) {
      const myChart = echarts.getInstanceByDom(echartsElement);
      if (myChart) {
        const svgData = myChart.getDataURL({ type: "svg" });
        if (!svgData.startsWith("data:image/svg+xml;charset=UTF-8,")) {
          // 这里可以添加一些处理逻辑，比如尝试重新获取，或者根据实际情况调整后续代码
          return;
        }

        // 提取 SVG 数据
        const rawSvgData = svgData.replace(
          "data:image/svg+xml;charset=UTF-8,",
          ""
        );
        const decodedSvg = decodeURIComponent(rawSvgData);

        // 创建一个新的 div 来包裹 SVG
        const svgDiv = document.createElement("div");
        svgDiv.innerHTML = decodedSvg;

        // 获取原 ECharts 容器的宽度和高度echartslist
        const containerWidth = echartsElement.offsetWidth;
        const containerHeight = echartsElement.offsetHeight;

        // 设置 SVG 的宽度和高度
        const svgElement = svgDiv.querySelector("svg");
        if (svgElement) {
          svgElement.setAttribute("width", `${containerWidth - 20}`);
          svgElement.setAttribute("height", `${containerHeight}`);

          // 确保 SVG 有命名空间
          if (!svgElement.hasAttribute("xmlns")) {
            svgElement.setAttribute("xmlns", "http://www.w3.org/2000/svg");
          }

          // 嵌入样式到 SVG
          const styleElement = document.createElementNS(
            "http://www.w3.org/2000/svg",
            "style"
          );
          styleElement.textContent = finalStyles;
          svgElement.insertBefore(styleElement, svgElement.firstChild);
        }

        // 替换 ECharts 容器为 SVG 容器
        echartsElement.parentNode.replaceChild(svgDiv, echartsElement);
      }
    }
    // 4. 为表格添加PDF专用样式
    const pdfStyles = `
      @page {
        size: A4;
        margin: 15mm 15mm 5mm 15mm; /* 上 右 下 左 */
      }
      /* 全局 CSS 或组件样式 */
      body {
        font-family: 'Arial', sans-serif;
        line-height: 1.6;
        color: #333;
        width: 100%;
        margin: 0;
        padding: 0;
        overflow: hidden !important;
      }
   
      .echartslist{
        width:29% !important;
     float: left!important;
     margin-left: 20px!important;
     border: 1px solid #ededed!important;
      }
      .details-echarts{
      
  width: 100%!important;
  height:300px!important;

      }

.echatys{
  float: left!important;
  width:48% !important;
  height:500px!important;

}
.echatys-rig{
  float: left!important;
  margin-left: 20px!important;
  width:48% !important;
  height:500px!important;

}
.Score-increase {
  margin-top: 30px!important;
}
.Score-increase-zhishi{
  width:100%!important;
  overflow: hidden !important;
}
.Score-increase-jineng{
  width:100%!important;
  overflow: hidden !important;
}
.Score-increase-nengli{
  width:100%!important;
  overflow: hidden !important;
}
.echatys-zhishi{
  float: left!important;
  width:48% !important;
  height:500px!important;
  border: 0px solid #ededed!important;

}
.echatys-rig-zhishi{
  float: left!important;
  margin-left: 20px!important;
  width:48% !important;
  height:500px!important;

}
.echatys-jineng{
  float: left!important;
  width:48% !important;
  height:500px!important;
  border: 0px solid #ededed!important;

}
.echatys-rig-jineng{
  float: left!important;
  margin-left: 20px!important;
  width:48% !important;
  height:500px!important;

}
.echatysopk{
  float: left!important;
  width:48% !important;
  height:500px!important;
  border: 0px solid #ededed!important;
}
.echatys-righul{
  float: left!important;
  margin-left: 20px!important;
  width:48% !important;
  height:500px!important;
}
.jianyi{
  float: left!important;
  height:500px!important;
}
.echartslistname{
  width:100%!important;
  overflow: hidden !important;
  height:700px!important;
}
.echatyslist{
  float: left!important;
  width:48% !important;
  height:100%!important;
  border: 0px solid #ededed!important;
}
.echatys-riglist{
  float: left!important;
  margin-left: 20px!important;
  width:48% !important;
  height:100%!important;
  border: 0px solid #ededed!important;

}

.imgdetails {
  background-image: url("/img/baogao.png");
  background-size: 100% 100%;

  position: relative;

}
 
      
//       .table-text {
//   margin-top: 10px;
//   font-size: 0.8vw;
//   text-align: left;
// }

      /* 分页控制 */
      .page-break {
        page-break-after: always !important;
      }
    
      .no-break {
        page-break-inside: avoid !important;
      }
      
      /* 确保自定义样式生效 */
      .content-detsils2 {
        height:100% !important;
        margin-top: 30px !important;
        page-break-inside: avoid !important;
        background-color: #fff !important;
      }
      
      /* 确保颜色和背景正确打印 */
      * {
        // -webkit-print-color-adjust: exact !important;
        // print-color-adjust: exact !important;
        background-color: #fff !important;
      }
    `;
    // 3. 创建包含样式的完整HTML      ${pdfStyles} ${finalStyles}
    const pageContent = `
      <!DOCTYPE html>
      <html>
        <head>
          <meta charset="UTF-8">
          <style>
          ${finalStyles}
          /* 添加PDF专用样式 */
          ${pdfStyles}
        </style>
        </head>
        <body>
          ${imgdetailsElement.outerHTML}
        </body>
      </html>
    `;

    /*if (pageContent) {
      const response = await MyHomeworkhtmltopdf({
        ctrID: route.query.CTRID,
        html: pageContent, // 现在包含完整样式
        //   `    <html>
        //    <head>
        //     <meta charset="UTF-8">
        //     <style></style>
        //   </head>
        //   <body>
        //     11
        //   </body>
        // </html>`
      });
      // // // 创建一个 Blob 对象，将 HTML 内容存储在其中
      // const blob = new Blob([pageContent], { type: "text/html" });
      // // // 生成一个指向 Blob 对象的临时 URL
      // const url = URL.createObjectURL(blob);

      // // 使用 window.open 打开新窗口
      // window.open(url, "_blank");

      const downloadUrl = `https://www.manfenbeikao.com/${response.url}`;
      window.open(downloadUrl, "_blank");
      pfdspin.value = false;
    }*/
  } catch (error) {
    console.error("生成PDF出错:", error);
    Message.error("PDF生成失败，请重试");
    pfdspin.value = false;
  }
};

const runturgo = () => {
  router.back();
};
// 定义按钮是否显示的响应式变量
const showButton = ref(false);

// 置顶函数，将所有.arco-layout 元素滚动到顶部
const primarytop = () => {
  const scrollBoxes = document.querySelectorAll(".arco-layout");
  scrollBoxes.forEach((box) => {
    (box as HTMLElement).scrollTo({
      top: 0,
      behavior: "smooth",
    });
  });
};

// 滚动事件处理函数，根据滚动距离控制按钮显示
const handleScroll = (event: Event) => {
  const target = event.target as HTMLElement;
  const scrollTop = target.scrollTop;
  const scrollLeft = target.scrollLeft;
  // 当滚动距离超过 500px 时显示按钮
  showButton.value = scrollTop > 500;
};
onMounted(() => {
  Report();
  // window.addEventListener('scroll', handleScroll);

  const scrollBoxes = document.querySelectorAll(".arco-layout");
  scrollBoxes.forEach((box) => {
    // 添加滚动事件监听器
    box.addEventListener("scroll", handleScroll);
  });
});
// 组件卸载时移除滚动事件监听器
onUnmounted(() => {
  const scrollBoxes = document.querySelectorAll(".arco-layout");
  scrollBoxes.forEach((box) => {
    // 移除滚动事件监听器，防止内存泄漏
    box.removeEventListener("scroll", handleScroll);
  });
});
</script>
<style lang="less" scoped>
.details {
  // width: 100vw;
  height: 100%;
  position: relative;
  // overflow: scroll;
}

.returngo {
  position: absolute;
  cursor: pointer;
  left: 0;
  top: -81px;
}

.imgdetails {
  background-image: url("/img/baogao.png");
  background-size: 100% 100%;
  position: relative;
}

.details-p {
  padding: 1.3vw 0 0 1.3vw;
  line-height: 25px;
  font-size: 0.8vw;
  font-weight: 500;
  color: #03305c;
}

.details-img {
  margin: 1.3vw 0 0 1.3vw;
  width: 77px;
  height: 77px;

  // background-color: pink;
  img {
    width: 100%;
    height: 100%;
  }
}

.content-area {
  height: 100%;
  margin: 0 2px;
  padding: 0 10vw;
  text-align: center;
  border-radius: 12px;
  background-color: #fff;
}

.content-detsils2 {
  margin-top: 5vw;
  page-break-inside: avoid;
  /* 防止元素内部跨页 */
  break-inside: avoid;
  /* 现代浏览器支持 */
  background-color: #fff;
}

.content-detsils3 {
  margin-top: 5vw;
  // background-color: pink;
  display: block;
  page-break-inside: avoid;
  /* 防止元素内部跨页 */
  break-inside: avoid;
  /* 现代浏览器支持 */
  // background-color: #fff;
}

.bottomlist {
  font-weight: 500;
  position: relative;
  bottom: 0;
  font-size: 0.8vw;
  padding: 1vw 0;
  color: #8393a3;
  text-align: center;
  height: 20px;
  //  background-color: pink;
  width: 100%;
}

.primary {
  position: fixed;
  bottom: 10%;
  right: 2vw;
  z-index: 999;
  color: #5b8ff9;
  font-size: 2vw;
}

.spinnu {
  text-align: center;
}

@media (max-width: 768px) {
  .returngo {
    position: absolute;
    cursor: pointer;
    left: 0;
    top: -50px;
  }
}
</style>
